<?php
namespace Admin\Common;

class Category
{
    /**
     * 获取分类等级列表
     * @param $cate
     * @param int $parent_id
     * @param int $level
     * @param string $delimiter
     * @return array
     */
    public static function toLevel($cate, $parent_id = 0, $level = 0, $delimiter = '|----')
    {
        $arr = [];
        foreach ($cate as $k => $v) {
            if ($v['parent_id'] == $parent_id) {
                $v['level'] = $level + 1;
                $v['delimiter'] = str_repeat($delimiter, $level);
                $arr[] = $v;
                $arr = array_merge($arr, self::toLevel($cate, $v['id'], $v['level'], $delimiter));
            }
        }
        return $arr;
    }

    /**
     * 判断是否存在子分类
     * @param $id 分类id
     * @return mixed
     */
    public static function isHaveChildren($id,$d='Cate')
    {
        $children = D($d)->where(['parent_id'=>$id])->field('id')->select();
        return $children;
    }

    /**
     * 判断分类下面是否存在商品
     * @param $ids
     * @return array|bool   存在 code=>1 反之 code=>0
     */
    public static function isHaveGoods($ids,$d='Stock')
    {
        try {
            if($d == 'Stock'){
                $goods = D('Stock')->where(['cat_id'=>$ids])->select();
            } elseif ($d == 'Food'){

                $goods = D('Food')->where(['cate_id'=>$ids])->select();
            }

            if(empty($goods)){
                // 说明此分类下没有库存商品
                return ['code'=>0];
            }else{
                // 存在商品
                return ['code'=>1];
            }
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * 传递一个父级分类ID返回所有子分类ID
     * @param $cate 全部分类数组
     * @param $pid 父级ID
     * @param  int $flag 是否包括父级自己的ID，默认不包括
     * @return mixed
     */
    static public function getChildsId($cate, $pid, $flag = 0)
    {
        $arr = array();
        if ($flag) {
            $arr[] = $pid;
        }
        foreach ($cate as $v) {
            if ($v['parent_id'] == $pid) {
                $arr[] = $v['id'];
                $arr = array_merge($arr , self::getChildsId($cate, $v['id']));
            }
        }
        return $arr;
    }
}